import React, { Component } from 'react'
import { Button, StyleSheet, View } from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { graphql, withApollo } from 'react-apollo'
import gql from 'graphql-tag'

import { Modal } from 'antd-mobile'
import { Icon, LoginForm } from '../components'
import { variables } from '../styles'

const AUTHENTICATE_MUTATION = gql`
  mutation($username: String!, $password: String!) {
    authenticate(username: $username, password: $password) {
      token
      userId
    }
  }
`

const USER_QUERY = gql`
  query {
    user {
      id
      username
      role
      name
    }
  }
`

@inject('actions', 'store')
@observer
@withApollo
@graphql(AUTHENTICATE_MUTATION, { name: 'authenticate' })
export class LoginScreen extends Component {
  componentDidMount() {
    if (process.env.NODE_ENV === 'development') {
      this.login({ username: 'alice', password: '<secret>' })
    }
  }

  login = async values => {
    try {
      const { actions, authenticate, client, navigation, store } = this.props

      const response = await authenticate({ variables: values })

      actions.login(response.data.authenticate)

      const { data: { user } } = await client.query({ query: USER_QUERY })

      store.user = user

      navigation.replace('Main')
    } catch (error) {
      Modal.alert('Error', String(error))
      console.warn('TODO', error)
    }
  }

  render = () => (
    <View style={styles.container}>
      <View style={styles.logo}>
        <Icon
          size={90}
          name="radio-button-off"
          color={variables.color_icon_base}
        />
      </View>
      <LoginForm onSubmit={this.login} />
      <Button
        title="Go to Register"
        onPress={() => this.props.navigation.replace('Register')}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: 'white',
  },
  logo: {
    alignItems: 'center',
    marginBottom: variables.v_spacing_xl,
  },
})
